package cn.st4rlight.util.execute;

import java.util.function.Supplier;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 降级工具
 *
 * @author st4rlight <st4rlight@163.com>
 * Created on 2024-05-04
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class FallbackUtil {

    /**
     * 带降级执行，不打印异常堆栈
     */
    public static void runFallback(Runnable runnable, Runnable fallback) {
        try {
            runnable.run();
        } catch (Exception ex) {
            log.warn("runFallback error: {}", ex.getMessage());
            fallback.run();
        }
    }

    /**
     * 带降级执行，打印异常堆栈
     */
    public static void runFallbackEx(Runnable runnable, Runnable fallback) {
        try {
            runnable.run();
        } catch (Exception ex) {
            log.error("runFallback error: {}", ex.getMessage(), ex);
            fallback.run();
        }
    }

    /**
     * 带降级获取，不打印异常堆栈
     */
    public static <T> T supplyFallback(Supplier<T> supplier, Supplier<T> fallback) {
        try {
            return supplier.get();
        } catch (Exception ex) {
            log.warn("supplyFallback error: {}", ex.getMessage());
            return fallback.get();
        }
    }

    /**
     * 带降级获取，打印异常堆栈
     */
    public static <T> T supplyFallbackEx(Supplier<T> supplier, Supplier<T> fallback) {
        try {
            return supplier.get();
        } catch (Exception ex) {
            log.error("supplyFallback error: {}", ex.getMessage(), ex);
            return fallback.get();
        }
    }
}
